<template>
  <div class="tw-main">
    <div class="screen">
      <el-row class="tw-grid">
        <el-col :md="24" :lg="12" class="tw-grid__left">
          <!-- <tw-card
          label="$t('m.collectionResource')">-->
          <tw-card label="集群资源"
            :heightCard="'357px'">
            <el-row>
              <el-col :span="6">
                <tw-echarts
                  id="echarts_colonyAppData"
                  ref="echarts_colonyAppData"
                  :additionalOptions="additionalOptions['echarts_colonyAppData']"
                  height="287px"
                ></tw-echarts>
              </el-col>
              <el-col :span="6">
                <tw-echarts
                  id="echarts_colonyServiceData"
                  ref="echarts_colonyServiceData"
                  :additionalOptions="additionalOptions['echarts_colonyServiceData']"

                  height="287px"
                ></tw-echarts>
              </el-col>

              <!--@finishCharts="simulation2('echarts_colonyServiceData')"
                @finishCharts="simulation2('echarts_colonyCPUData')"
                @finishCharts="simulation2('echarts_colonyRAMData')"-->
              <el-col :span="6">
                <tw-echarts
                  id="echarts_colonyCPUData"
                  ref="echarts_colonyCPUData"
                  :additionalOptions="additionalOptions['echarts_colonyCPUData']"
                  height="287px"
                ></tw-echarts>
              </el-col>
              <el-col :span="6">
                <tw-echarts
                  id="echarts_colonyRAMData"
                  ref="echarts_colonyRAMData"
                  :additionalOptions="additionalOptions['echarts_colonyRAMData']"

                  height="287px"
                ></tw-echarts>
              </el-col>
            </el-row>
          </tw-card>
        </el-col>
        <el-col :md="24" :lg="12" class="tw-grid__right">
          <!-- <tw-card
          label="$t('m.colonyRequestCount')">-->
          <tw-card label="集群请求数"
           :heightCard="'357px'">
            <tw-echarts
              id="echarts_clusterRequest"
              ref="echarts_clusterRequest"
              :additionalOptions="additionalOptions['echarts_clusterRequest']"
              height="287px"
              @finishCharts="simulation1"
            ></tw-echarts>
          </tw-card>
          <!-- <tw-card label="集群请求数">
              <tw-chart :options="dataOptions" height="292px"></tw-chart>
          </tw-card> -->
        </el-col>
      </el-row>
      <el-row class="tw-grid">
        <el-col :span="24" class="tw-grid__single">
          <!-- <tw-card
          label="$t('m.serverMonitorInfo')"-->
          <tw-card label="服务器监控信息"
            :heightCard="'270px'"
            :rightLabel="rightLabel" :grayRightLabel="true">
            <ul class="tw-ul">
              <li v-for="item in hostMonitoring" v-bind:key="item.id" style="width:19.9%">
                <div class="tw-server-info">
                  <div class="tw-server-info__left">
                    <img :src="'/static/weishidataview/images/' + item.img" alt="container" />
                  </div>
                  <div class="tw-server-info__right">
                    <p>{{item.name}}</p>
                    <p class="digi" style="font-size:40px">
                      {{item.info}}
                      <span class="unit" v-if="item.unit">{{item.unit}}</span>
                    </p>
                  </div>
                </div>
              </li>
            </ul>
          </tw-card>
        </el-col>
      </el-row>
      <el-row class="tw-grid">
        <el-col :span="24" class="tw-grid__single">
          <tw-card
            :heightCard="'270px'"
            label="Redis Cluster 状态监控">
            <ul class="tw-status" v-if="clusterStatus&&clusterStatus.length>0">
              <li v-for="item in clusterStatus" v-bind:key="item.id">
                  <img src="/static/weishidataview/images/main.png" alt="main">
                  <div class="tw-status__info">
                    <p>{{item.cluster === '1' ? '主': item.cluster === '2' ? '备' : '单'}}</p>
                    <p class="port">{{ "端口" + item.port}}</p>
                    <div v-if="item.state === '1'" class="tw-status__info-img">
                      <img class="warning" src="/static/weishidataview/images/ok.png" alt="warning">
                    </div>
                    <div v-if="item.state === '2'" class="tw-status__info-img">
                      <img class="warning" src="/static/weishidataview/images/warning.png" alt="warning">
                    </div>
                  </div>
              </li>
            </ul>
            <div class="zwsj">
              暂无数据
            </div>
          </tw-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script scoped>
import echarts from 'echarts'
import TwCard from '@/components/TwCard'
import TwEcharts from '@/components/TwEcharts'
import configUtil from '@/config/config'
import TwChart from '@/components/TwChart.vue'

export default {
  created () {
    let vm = this
    // 应用分类数据
    // this.$axios.post(configUtil.getApiPath() + 'app/queryAppCatagoryStatistics', null).then(response => {
    //   if (response && response.data.pageInfo.list && response.data.pageInfo.list.length > 0) {
    //     let appCount = 0
    //     for (let i = 0; i < response.data.pageInfo.list.length; i++) {
    //       appCount += response.data.pageInfo.list[i].totalCount
    //     }
    //     let appCataItem = {
    //       'name': this.$i18n.messages[this.$i18n.locale].m.app,
    //       'data': appCount
    //     }
    //     vm.additionalOptions.echarts_colonyAppData = appCataItem
    //   } else {
    //     console.log('queryAppCatagoryStatistics data null ....................')
    //   }
    // }, response => {
    //   console.log('queryAppCatagoryStatistics error')
    // })

    // vm.clusterStatusObj[0].port.forEach(function (item, index) {
    //   vm.clusterStatus.push({
    //     port: item
    //   })
    // })
    // let len = vm.clusterStatus.length

    // for (let i = 0; i < len; i++) {
    //   vm.clusterStatus[i].cluster = ''
    //   vm.clusterStatus[i].state = ''
    //   vm.clusterStatus[i].cluster = vm.clusterStatusObj[0].cluster[i]
    //   vm.clusterStatus[i].state = vm.clusterStatusObj[0].state[i]
    // }
    // console.log('clusterStatus========================', vm.clusterStatus)

    // vm.clusterStatusObj[0].state.forEach(function (item, index) {
    //   vm.clusterStatus.push({
    //     state: item
    //   })
    // })

    vm.ServiceMonitoring()

    this.time3 = setInterval(vm.ServiceMonitoring, 60000)

    // echarts_clusterRequest 集群请求数
    vm.$axios
      .get(
        window.location.origin +
          '/static/weishidataview/jsondata/echarts_clusterRequest.json'
      )
      .then(
        (response) => {
          vm.additionalOptions.echarts_clusterRequest = response.data
        },
        (response) => {
          console.log('error')
        }
      )
    // REDIUS 列表
    // vm.$axios.post(configUtil.getApiPath() + 'server/getRediusList', null).then(response => {
    //   if (response && response.data.pageInfo && response.data.pageInfo.list && response.data.pageInfo.list.length > 0) {
    //     for (let i = 0; i < response.data.pageInfo.list.length; i++) {
    //       let status = response.data.pageInfo.list[i].status === '1' ? 'OK' : 'warning'
    //       let item = {
    //         id: i + 1,
    //         name: response.data.pageInfo.list[i].hostName,
    //         port: response.data.pageInfo.list[i].hostPort,
    //         status: status
    //       }
    //       vm.clusterStatus.push(item)
    //     }
    //   } else {
    //     console.log('getRediusList data null ....................')
    //   }
    // }, response => {
    //   console.log('getRediusList error')
    // })
  },
  mounted () {
    window.onresize = () => {
      this.$refs['echarts_colonyAppData'].resizeChart()
      this.$refs['echarts_colonyServiceData'].resizeChart()
      this.$refs['echarts_colonyCPUData'].resizeChart()
      this.$refs['echarts_colonyRAMData'].resizeChart()
      this.$refs['echarts_clusterRequest'].resizeChart()
    }
  },
  data () {
    return {
      time1: null,
      time2: null,
      time3: null,
      dataOptions: {
        'series': [
          {
            'data': [
              820.0,
              932.0,
              901.0,
              934.0,
              1290.0,
              1330.0,
              1320.0
            ],
            'type': 'line',
            'areaStyle': {
              'color': '#04BDD3'
            },
            'lineStyle': {
              'color': '#07F2F6',
              'width': 3.0
            },
            'smooth': true,
            'name': null
          }
        ],
        'xAxis': {
          'type': 'category',
          'boundaryGap': false,
          'data': [
            'Mon',
            'Tue',
            'Wed',
            'Thu',
            'Fri',
            'Sat',
            'Sun'
          ]
        },
        'yAxis': {
          'type': 'value'
        }
      },
      additionalOptions: {
        echarts_colonyAppData: {},
        echarts_colonyServiceData: {},
        echarts_colonyCPUData: {},
        echarts_colonyRAMData: {},
        echarts_clusterRequest: {}
      },
      rightLabel: '',
      hostMonitoring: [
        {
          id: 1,
          name: 'Docker',
          info: '2',
          img: 'container.png'
        },
        {
          id: 2,
          name: 'Master',
          info: '28/28',
          img: 'host.png'
        },
        {
          id: 3,
          name: 'Storage',
          info: '11',
          unit: 'TB',
          img: 'storage.png'
        },
        {
          id: 4,
          name: 'CPU',
          info: '32.10',
          unit: '%',
          img: 'cpu.png'
        },
        {
          id: 5,
          name: 'Memory',
          info: '20.6',
          unit: '%',
          img: 'ram.png'
        }
      ],
      clusterStatus: [
        // 最多支持9个！
      ],
      simulation2Flag: false
    }
  },
  props: [],
  methods: {
    simulation1: function () {
      let chart = echarts.init(
        document.getElementById('echarts_clusterRequest')
      )
      let chartOption = chart.getOption()
      this.time1 = setInterval(() => {
        chartOption.series[0].data.shift()
        chartOption.series[0].data.push(parseInt(Math.random() * 1000))
        chartOption.xAxis[0].data.shift()
        chartOption.xAxis[0].data.push(new Date().toTimeString().slice(0, 8))
        chart.setOption(chartOption)
      }, 1000)
    },
    simulation2: function (id) {
      let chart = echarts.init(document.getElementById(id))
      let chartOption = chart.getOption()
      this.time2 = setInterval(() => {
        chartOption.series[0].data = []
        let temp = (Math.random() * 100).toFixed(1)
        chartOption.series[0].data.push({
          value: temp
        })
        chartOption.series[0].data.push({
          value: 100 - temp,
          label: {
            show: false
          },
          itemStyle: {
            color: '#05388f'
          }
        })
        chart.setOption(chartOption)

        if (id === 'echarts_colonyCPUData') {
          this.hostMonitoring[3].info = temp
        } else if (id === 'echarts_colonyRAMData') {
          this.hostMonitoring[4].info = temp
        }
      }, 5000)
    },

    // 服务监控
    ServiceMonitoring () {
      let vm = this
      vm.$axios
        .post(configUtil.getServicePath() + '/v1/dash/main', {
          hostnameList: configUtil.hostnameList
        })
        .then(
          (res) => {
            if (
              res.data.serverResult &&
            res.data.serverResult.resultCode === '200'
            ) {
              let resData = res.data.responseEntity
              // 集群资源应用
              vm.additionalOptions.echarts_colonyAppData = {
                note: '集群资源应用',
                name: '应用',
                data: resData.appCount
              }
              // 集群资源服务器
              vm.additionalOptions.echarts_colonyServiceData = {
                note: '集群资源服务器',
                name: '服务器',
                data: resData.maxFifteenSystemLoadPer.replace('%', '')
              }
              // 集群资源CPU
              vm.additionalOptions.echarts_colonyCPUData = {
                note: '集群资源CPU',
                name: 'CPU(核)',
                data: resData.avgCpuPer.replace('%', '')
              }
              // 集群资源内存
              vm.additionalOptions.echarts_colonyRAMData = {
                note: '集群资源内存',
                name: '内存(MB)',
                data: resData.avgMemoryPer.replace('%', '')
              }

              // 服务器监控信息
              vm.hostMonitoring = [
                {
                  id: 1,
                  name: 'Docker',
                  info: resData.dockerCount,
                  img: 'container.png'
                },
                {
                  id: 2,
                  name: 'Master',
                  info: resData.onlineMasterCount + '/' + resData.masterCount,
                  img: 'host.png'
                },
                {
                  id: 3,
                  name: 'Storage',
                  info: resData.storageTotalSize,
                  unit: 'GB',
                  img: 'storage.png'
                },
                {
                  id: 4,
                  name: 'CPU',
                  info: resData.avgCpuPer.replace('%', ''),
                  unit: '%',
                  img: 'cpu.png'
                },
                {
                  id: 5,
                  name: 'Memory',
                  info: resData.avgMemoryPer.replace('%', ''),
                  unit: '%',
                  img: 'ram.png'
                }
              ]

              vm.rightLabel = resData.monitorServerTime

              // 状态监控
              vm.clusterStatus = []
              if(resData.redisStateList&&resData.redisStateList.length>0){
                resData.redisStateList[0].port.forEach(function (item, index) {
                  vm.clusterStatus.push({
                    port: item
                  })
                })
              }
              let len = vm.clusterStatus.length
              for (let i = 0; i < len; i++) {
                vm.clusterStatus[i].cluster = ''
                vm.clusterStatus[i].state = ''
                vm.clusterStatus[i].cluster = resData.redisStateList[0].cluster[i]
                vm.clusterStatus[i].state = resData.redisStateList[0].state[i]
              }
            }
          },
          (res) => {
            console.log('error')
          }
        )
    }
  },
  components: {
    TwCard,
    TwEcharts,
    TwChart
  },
  beforeDestroy () {
    if (this.time1) {
      clearInterval(this.time1)
    }
    if (this.time2) {
      clearInterval(this.time2)
    }
    if (this.time3) {
      clearInterval(this.time3)
    }
  }
}
</script>

<style scoped>
.zwsj{
  height: 214px;
  text-align: center;
  line-height: 214px;
  font-size: 20px;
}
</style>
